package com.echo.activity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.activeandroid.Model;
import com.activeandroid.query.Select;
import com.echo.SportsApplication;
import com.echo.fragment.AccountFragment;
import com.echo.fragment.ExploreFragment;
import com.echo.fragment.HistoryFragment;
import com.echo.fragment.SportsFragment;
import com.echo.http.HttpCallBack;
import com.echo.http.HttpManager;
import com.echo.http.HttpUrl;
import com.echo.model.DayData;
import com.echo.model.Sport;
import com.echo.util.ActiveAndroidStrategy;
import com.echo.util.Base64Util;
import com.echo.util.DrawableUtil;
import com.echo.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import net.iharder.Base64;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cz.msebera.android.httpclient.Header;

public class SportsActivity extends AppCompatActivity {

    private FragmentManager mFragmentManager;
    private FragmentTransaction mFragmentTransaction;
    private Fragment mSportsFragment, mHistoryFragment, mExploreFragment, mAccountFragment;
    private Fragment mCurrentFragment = null;

    private ImageButton mSport, mHistory, mExplore, mAccount;


    private String[] mTitles;
    private Toolbar mToolbar;
    private TextView mTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);

        initActionBar();
        initView();
        initFragment();

        //ActiveAndroid.execSQL("drop table if exists sports");
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void initActionBar() {
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        //toolbar.setTitle("今日运动");
        setSupportActionBar(mToolbar);
        mTitle = (TextView) findViewById(R.id.toolbar_title);
    }

    private void initView() {
        mTitles = getResources().getStringArray(R.array.tabs);
        mSport = (ImageButton) findViewById(R.id.tab_sport);
        mHistory = (ImageButton) findViewById(R.id.tab_history);
        mExplore = (ImageButton) findViewById(R.id.tab_explore);
        mAccount = (ImageButton) findViewById(R.id.tab_account);
        mSport.setImageDrawable(DrawableUtil.tintListDrawable(mSport.getDrawable(), getResources().getColorStateList(R.color.tab_tint)));
        mHistory.setImageDrawable(DrawableUtil.tintListDrawable(mHistory.getDrawable(), getResources().getColorStateList(R.color.tab_tint)));
        mExplore.setImageDrawable(DrawableUtil.tintListDrawable(mExplore.getDrawable(), getResources().getColorStateList(R.color.tab_tint)));
        mAccount.setImageDrawable(DrawableUtil.tintListDrawable(mAccount.getDrawable(), getResources().getColorStateList(R.color.tab_tint)));
        mSport.setTag(0);
        mHistory.setTag(1);
        mExplore.setTag(2);
        mAccount.setTag(3);
        mSport.setOnClickListener(new MyOnClickListener());
        mHistory.setOnClickListener(new MyOnClickListener());
        mExplore.setOnClickListener(new MyOnClickListener());
        mAccount.setOnClickListener(new MyOnClickListener());
    }

    private void initFragment() {
        mFragmentManager = getSupportFragmentManager();
        goToFragment(0);
    }


    public void goToFragment(int id) {
        mTitle.setText(mTitles[id]);
        mSport.setSelected(id == 0);
        mHistory.setSelected(id == 1);
        mExplore.setSelected(id == 2);
        mAccount.setSelected(id == 3);
        mFragmentTransaction = mFragmentManager.beginTransaction();
        if (mCurrentFragment != null)
            mFragmentTransaction.hide(mCurrentFragment);
        switch (id) {
            case 0:
                if (mSportsFragment == null) {
                    mSportsFragment = new SportsFragment();
                    mFragmentTransaction.add(R.id.frame, mSportsFragment, mSportsFragment.getClass().getName());
                } else {
                    mFragmentTransaction.show(mSportsFragment);
                }
                mCurrentFragment = mSportsFragment;
                break;
            case 1:
                if (mHistoryFragment == null) {
                    mHistoryFragment = new HistoryFragment();
                    mFragmentTransaction.add(R.id.frame, mHistoryFragment, mHistoryFragment.getClass().getName());
                } else {
                    mFragmentTransaction.show(mHistoryFragment);
                }
                mCurrentFragment = mHistoryFragment;
                break;
            case 2:
                if (mExploreFragment == null) {
                    mExploreFragment = new ExploreFragment();
                    mFragmentTransaction.add(R.id.frame, mExploreFragment, mExploreFragment.getClass().getName());
                } else {
                    mFragmentTransaction.show(mExploreFragment);
                }
                mCurrentFragment = mExploreFragment;
                break;
            case 3:
                if (mAccountFragment == null) {
                    mAccountFragment = new AccountFragment();
                    mFragmentTransaction.add(R.id.frame, mAccountFragment, mAccountFragment.getClass().getName());
                } else {
                    mFragmentTransaction.show(mAccountFragment);
                }
                mCurrentFragment = mAccountFragment;
                break;
        }
        mFragmentTransaction.commit();
    }

    private class MyOnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            goToFragment((Integer) v.getTag());
        }
    }


    public void tologin(View view) {
        Intent it = new Intent();
        it.setClass(SportsActivity.this, LoginActivity.class);
        startActivity(it);
    }

    public void toregist(View view) {
        Intent it = new Intent();
        it.setClass(SportsActivity.this, RegistActivity.class);
        startActivity(it);
    }

    private boolean is_uploading=false;
    public final Object object=new Object();

    public void upload_all(View view) throws JSONException {
        if(!is_uploading) {
            synchronized (object) {
                is_uploading = true;
            }
            Thread thread=new Thread(new Runnable() {
                @Override
                public void run() {
                    Gson gson = new GsonBuilder().setExclusionStrategies(new ActiveAndroidStrategy(null, Model.class)).serializeNulls().create();
                    List<DayData> dayDatas = new Select().from(DayData.class).where("user_id=?",SportsApplication.getInstance().getUserId()).execute();
                    List<Sport> sports = new Select().from(Sport.class).execute();
                    for(int i=0;i<sports.size();i++){
                        Sport sport=sports.get(i);
                        byte[] image=sport.getSnapshot();
                        //sport.setSnapshotUrl(Base64.encodeBytes(image));
                    }
                    List list = new ArrayList();
                    list.add(dayDatas);
                    list.add(sports);
                    RequestParams params = new RequestParams();
                    params.put("json",gson.toJson(list));
                    String url = HttpUrl.URL_UPLOAD_DATA ;


                    AsyncHttpClient client = new AsyncHttpClient();
                    client.post(url, params, new AsyncHttpResponseHandler() {
                        @Override
                        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                            synchronized (object) {
                                is_uploading = false;
                            }
                            Toast.makeText(SportsActivity.this,"同步成功",Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                            synchronized (object) {
                                is_uploading = false;
                            }
                            Toast.makeText(SportsActivity.this,"同步失败",Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            });
            thread.start();

            /*String str = gson.toJson(list);
            String url = HttpUrl.URL_UPLOAD_DATA + "?json=" + str;*/
            /*HttpManager.getInstance().upload_data(url, new HttpCallBack() {
                @Override
                public void onMsg(Object response) throws JSONException {
                    ToastUtils.show(SportsActivity.this,"同步成功", Toast.LENGTH_SHORT);
                    synchronized (object) {
                        is_uploading = false;
                    }
                }

                @Override
                public void onError() {

                    ToastUtils.show(SportsActivity.this,"同步失败", Toast.LENGTH_SHORT);
                }
            });*/
        }else{
            Toast.makeText(SportsActivity.this,"正在同步",Toast.LENGTH_SHORT).show();
        }
    }

    private boolean is_downloading=false;

    public void download_all(View view) {
        if(!is_downloading){
            synchronized (object) {
                is_downloading = true;
            }

            String url=HttpUrl.URL_DOWNLOAD_DATA+"?id="+20;
            HttpManager.getInstance().download_data(url, new HttpCallBack() {
                @Override
                public void onMsg(final Object response) throws JSONException {
                    Thread thread=new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                JSONArray jsonArray = (JSONArray) response;
                                JSONArray dayDataArray = jsonArray.getJSONArray(0);
                                JSONArray sportArray = jsonArray.getJSONArray(1);
                                for (int i = 0; i < dayDataArray.length(); i++) {
                                    JSONObject object = dayDataArray.getJSONObject(i);
                                    DayData dayData = new DayData();
                                    dayData.setId(object.getLong("id"));
                                    dayData.setDistance(object.getInt("distance"));
                                    dayData.setTime(object.getInt("time"));
                                    dayData.setDate(object.getString("date"));
                                    dayData.setRank(object.getInt("rank"));
                                    dayData.setSteps(object.getInt("steps"));
                                    dayData.setCalories(object.getInt("calories"));
                                    dayData.save();
                                }
                                for (int i = 0; i < sportArray.length(); i++) {
                                    JSONObject object = sportArray.getJSONObject(i);
                                    Sport sport = new Sport();
                                    sport.setId(object.getInt("id"));
                                    sport.setCalories(object.getInt("calories"));
                                    sport.setDate(object.getString("date"));
                                    sport.setTime(object.getInt("time"));
                                    sport.setUserId(object.getLong("userId"));
                                    sport.setType(object.getInt("type"));
                                    sport.setSnapshotUrl(object.getString("snapshotUrl"));
                                    JSONObject startTime=object.getJSONObject("start");
                                    JSONObject startTime1=startTime.getJSONObject("time");
                                    long time=startTime1.getLong("time");
                                    Date date=new Date();
                                    date.setTime(time);
                                    Calendar cl=Calendar.getInstance();
                                    cl.setTime(date);
                                    sport.setStart(cl);
                                    sport.save();
                                    //Toast.makeText(SportsActivity.this,"同步成功",Toast.LENGTH_SHORT).show();
                                }
                            }catch (Exception e){
                                e.printStackTrace();
                                //Toast.makeText(SportsActivity.this,"同步失败",Toast.LENGTH_SHORT).show();
                            }finally {
                                synchronized (object) {
                                    is_downloading = false;
                                }

                            }
                        }
                    });
                    thread.start();
                }

                @Override
                public void onError() {

                    synchronized (object) {
                        is_downloading = false;
                    }
                    //Toast.makeText(SportsActivity.this,"同步失败",Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    public void to_community(View view) {
        Intent it = new Intent(SportsActivity.this, CommunityActivity.class);
        startActivity(it);
    }

    public void to_music(View view) {
        Intent it = new Intent();
        it.setClass(SportsActivity.this, MusicActivity.class);
        startActivity(it);
    }

    public void to_friends(View view) {
        if(SportsApplication.getInstance().isLogin()) {
            Intent it = new Intent(SportsActivity.this, FriendsActivity.class);
            startActivity(it);
        }else{
            Toast.makeText(SportsActivity.this,"没有登录",Toast.LENGTH_SHORT).show();
        }
    }

    public void to_galley(View view) {
        Intent it = new Intent(SportsActivity.this, GalleryActivity.class);
        startActivity(it);
    }

    public void to_personal(View view) {
        if (SportsApplication.getInstance().isLogin()) {
            Intent it=new Intent(SportsActivity.this,PersonalActivity.class);
            startActivity(it);
        } else {
            Intent it = new Intent();
            it.setClass(SportsActivity.this, LoginActivity.class);
            startActivity(it);
        }
    }

}
